package com.example.sample.activity;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.example.app.BaseActivity;
import com.example.sample.R;

public class DirtyRectActivity extends BaseActivity implements SurfaceHolder.Callback{
	
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private WorkThread mThread = new WorkThread();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dirty_rect);
		mSurfaceView = (SurfaceView)findViewById(R.id.surface);
		mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceHolder.addCallback(this);
	}
	
	public class WorkThread extends Thread{
		private boolean mStop = false;
		private int mFrame = 0;
		public void run() {
			while (!interrupted() && !mStop) {
				try {
					sleep(1000);
				} catch (InterruptedException e) {
				}
				draw(mFrame++);	
			}
		};	
		public void stopThread(){
			mStop = true;
			try {
				join();
			} catch (InterruptedException e) {
			}
		}
	}
	
	private void draw(int frame){
		Paint paint = new Paint();
		paint.setColor(Color.parseColor("red"));
		paint.setTextSize(16f);
		Canvas canvas = null;
        try {
        	canvas = mSurfaceHolder.lockCanvas();
        	String text = ""+frame;
            canvas.drawText(text, 20*frame, 111, paint);
        } catch (Exception e) {        	
        } finally{
            if (canvas != null){
            	try {
            		mSurfaceHolder.unlockCanvasAndPost(canvas);
				} catch (Exception e2) {
				}
            }
        }
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		mThread.start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mThread.stopThread();
	}
}
